import axios from 'axios'
import { Message } from 'element-ui'
import router from '../router'
import store from '../store'
import { getTimeStamp } from '../utils/auth'
const TimeOut = 3600
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000
})

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    const _token = store.getters.token
    if (_token) {
      if (IsCheckTimeOut()) {
        store.dispatch('user/logout')
        router.push('/login')
        return Promise.reject(new Error('token超时了'))
      }
      config.headers.Authorization = `Bearer ${_token}`
    }
    return config
  },
  (error) => {
    if (error.response && error.response.data && error.response.data.code === 10002) {
      store.dispatch('user/logout')
      router.push('/login')
    } else {
      Message.error(error.message)
    }
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(response => {
  const { message, success, data } = response.data

  if (success) {
    return data
  } else {
    Message.error(message)
    return Promise.reject(new Error(message))
  }
}, error => {
  // Message.error(error.message)
  return Promise.reject(error)
})
function IsCheckTimeOut() {
  const currentTime = Date.now() // 当前时间
  const timeStamp = getTimeStamp() // 缓存中的时间
  return (currentTime - timeStamp) / 1000 > TimeOut
}

export default service

